package com.ezops.poc.validations.validators;

import java.lang.reflect.Field;

import com.ezops.poc.validations.result.FieldValidationError;
import com.ezops.poc.validations.result.ValidationResult;

/**
 * Checks if the field being passed is present in the model under test
 * 
 * @author vgaurav
 * 
 */
public class MandatoryValidator implements IValidators {

	private  String fieldName;

	public MandatoryValidator() {
		
	}

	@Override
	public ValidationResult validate(Object model) {
		if (model == null) {
			throw new IllegalArgumentException("Can't not validate null model");
		}
		 Object value;

		try {
			final Field field = model.getClass().getDeclaredField(fieldName);
			field.setAccessible(true);
			value = field.get(model);
			if (value != null && !value.toString().trim().equals("")) {
				return ValidationResult.getValidResponse();
			}
		} catch (Exception ex) {
			try {
				final Field field = model.getClass().getField(fieldName);
				field.setAccessible(true);
				value = field.get(model);
				if (value != null && !value.toString().trim().equals("")) {
					return ValidationResult.getValidResponse();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		return ValidationResult.getErrorResponse(new FieldValidationError() {

			public String getFieldName() {
				return fieldName;
			}

			public String getErrorMessage() {
				return "The field name " + fieldName + " is not present.";
			}
		});

	}

	public void init(String fieldName, String... values) {
		this.fieldName = fieldName;
	}
}
